import { TIME_INTERVAL } from '@/assets/constant/other-constants';
import { ComponentWithComputed } from 'miniprogram-computed';
import lunarFun from 'lunar-fun';

ComponentWithComputed({
  properties: {
    scheduleData: {
      type: Array,
      value: [],
    },
  },
  data: {
    activeIndex: 0,
    currentPanelMonth: `${new Date().getFullYear()}-${new Date().getMonth() + 1}`,
    yellowTimeInterval: TIME_INTERVAL.slice(0, 3),
  },
  computed: {
    markList(properties) {
      const MARK_TEMPLATE = {
        date: '',
        type: 'dot',
      };
      const markList = (properties.scheduleData as ScheduleDataByYear)
        .map((item) => item.scheduleDataByMonth)
        .flat()
        .map((item) => item.scheduleList)
        .flat()
        .reduce((prev: ResScheduleInfoItem[], current) => {
          return prev.find((item) => item.date === current.date) ? prev : [...prev, current];
        }, [])
        .map((item) => {
          const [year, month, day] = item.date.split('-');
          const lunarDay = lunarFun
            .formatLunarDate(...lunarFun.gregorianToLunal(Number(year), Number(month), Number(day)))
            .split('月')[1]
            .slice(0, 2);
          return {
            ...MARK_TEMPLATE,
            date: `${year}-${month}-${day}`,
            bottomInfo: lunarDay,
          } as Mark;
        });

      return markList;
    },
    currentShowScheduleList(data) {
      const { currentPanelMonth, scheduleData } = data;
      if (!scheduleData) return [];
      const year = Number(currentPanelMonth.split('-')[0]);
      const month = Number(currentPanelMonth.split('-')[1]);
      const currentYearScheduleData = (scheduleData as ScheduleDataByYear).find((item) => item.year === year);
      const currentMonthScheduleData = currentYearScheduleData?.scheduleDataByMonth.find((item) => item.month === month);
      return currentMonthScheduleData?.scheduleList || [];
    },
  },
  methods: {
    onClickSwitch(e: WechatMiniprogram.TouchEvent) {
      const { index } = e.currentTarget.dataset;
      this.setData({
        activeIndex: Number(index),
      });
    },
    onChangePanel(e: WechatMiniprogram.CustomEvent) {
      this.setData({
        currentPanelMonth: `${e.detail.year}-${e.detail.month.toString().padStart(2, '0')}`,
      });
    },
    onClickScheduleCard(e: WechatMiniprogram.TouchEvent) {
      wx.navigateTo({
        url: `/subpkg/pages/schedule-detail/schedule-detail?scheduleId=${e.currentTarget.dataset.schedule_id}`,
      });
    },
    onClickPhone(e: WechatMiniprogram.TouchEvent) {
      wx.makePhoneCall({
        phoneNumber: e.currentTarget.dataset.customer_phone,
      });
    },
  },
});
